package model

import (
	"fmt"
	"notes/config"
	"notes/util"
	"time"

	"github.com/things-go/gormzap"

	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// 数据库
var DB *gorm.DB

func init() {
	var (
		err error
	)

	newLogger := gormzap.New(util.Logger,
		gormzap.WithConfig(logger.Config{
			SlowThreshold:             200 * time.Millisecond,
			Colorful:                  false,
			IgnoreRecordNotFoundError: false,
			LogLevel:                  logger.Info,
		}),
	)

	ormConfig := &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
		SkipDefaultTransaction:                   true,
		Logger:                                   newLogger,
	}

	uri := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.Conf.MysqlConfig.User,
		config.Conf.MysqlConfig.Password,
		config.Conf.MysqlConfig.Host,
		config.Conf.MysqlConfig.Port,
		config.Conf.MysqlConfig.DB,
	)
	DB, err = gorm.Open(mysql.Open(uri), ormConfig)
	if err != nil {
		DB, err = gorm.Open(sqlite.Open("database.db"), ormConfig)
	}

	if err != nil {
		util.Logger.Error(uri)
		panic(fmt.Sprintf("链接数据库失败:%v\n", err))
	}

	DB.AutoMigrate(&Article{}, &Category{}, Tag{})
}
